﻿//using System;
//using System.Collections.Generic;
//using System.ComponentModel;
//using System.Drawing;
//using System.Data;
//using System.Linq;
//using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace pnhBrowserControl
{
    public partial class pnhBowserControl : UserControl
    {
        private string _finalString;
        private bool _srcReceived;
        private mshtml.HTMLDocument _doc;
        private const int _maxReload = 3;
        private string _textToDetect;
        private bool _loadActivity;
        private bool _bThreadStarted;
        private bool _bDefaultNavigate;
        #region Log

        /// <summary>
        /// Delegate for the log function
        /// </summary>
        /// <param name="str"></param>
        private delegate void logDelegate(string str);

        /// <summary>
        /// Log a string
        /// </summary>
        /// <param name="str"></param>
        private void log(string str)
        {
            if (console.InvokeRequired)
            {
                logDelegate del = new logDelegate(log);
                console.Invoke(del, new object[] { str + "\n" });
            }
            else
            {
                console.AppendText(str + "\n");
            }
        }
        #endregion

        /// <summary>
        /// Constructor
        /// </summary>
        public pnhBowserControl()
        {
            InitializeComponent();
            log("****CONSOLE BROWSER****");
        }

        /// <summary>
        /// Detect when a list of game is loaded
        /// </summary>
        private void checkGamesListLoaded()
        {
            _finalString = _doc.documentElement.innerHTML;
            if (_finalString == null)
            {
                _finalString = "ERROR";
                _srcReceived = true;
                return;
            }
            int count = 0;

            bool over = false;
            while (!over)
            {
                log("--Count : " + count.ToString());
                Thread.Sleep(1000);
                _finalString = _doc.documentElement.innerHTML;
                if (_finalString == null)
                {
                    _finalString = "ERROR";
                    _srcReceived = true;
                    return;
                }
                over = _finalString.Contains("terminé(s)");
                log("--OVER : " + over.ToString());
                if (over)
                    break;
                if (_finalString.Contains("Internet Explorer ne peut pas afficher cette page Web"))
                {
                    _finalString = "ERROR";
                    over = true;
                }
                //else if (_finalString.Contains("Se connecter"))
                //{
                //    _finalString = "ERROR";
                //    over = true;
                //}

                ++count;
                if (count >= 15)
                {
                    _finalString = "ERROR";
                    _srcReceived = true;
                    return;
                }
            }
            log("--Received = TRUE");
            _srcReceived = true;
            return;
        }

        /// <summary>
        /// Detect when a list of achievement is loaded
        /// </summary>
        private void checkAchievementsListLoaded()
        {
            int count = 0;
            bool over = false;
            while (!over)
            {
                Thread.Sleep(1000);
                over = _finalString.Contains("<script id=\"comparisonTemplate\" type=\"text/x-jquery-tmpl\">");
                if (_finalString.Contains("Internet Explorer ne peut pas afficher cette page Web"))
                {
                    _finalString = "ERROR";
                    over = true;
                }

                ++count;
                if (count >= 15)
                {
                    _finalString = "ERROR";
                    _srcReceived = true;
                    return;
                }

            }
            _srcReceived = true;

        }

        /// <summary>
        /// Request a web page containing a list of achievements
        /// </summary>
        /// <param name="url">complete url of the page to get</param>
        /// <returns></returns>
        public string getWebPageAchievement(string url)
        {
            _loadActivity = false;
            _bDefaultNavigate = false;
            //reload count
            int reloadCount = 0;

            //while the reload count does not exceed the max reload count
            while (reloadCount < _maxReload)
            {
                //request the page
                //navigate(url);
                _srcReceived = false;
                webBrowser.Navigate(url);

                //wait for an answer
                while (!_srcReceived)
                {
                    Thread.Sleep(100);
                }

                _bThreadStarted = false;
                //if error then reload
                if (_finalString == "ERROR")
                    ++reloadCount;
                else
                    //return browser.DocumentText;
                    return _finalString;
            }

            return _finalString;
        }

        /// <summary>
        /// Request a web page containing a list of games
        /// </summary>
        /// <param name="url">complete url of the page to get</param>
        /// <param name="gamertag">player's gamertag</param>
        /// <returns></returns>
        public string getWebPageActivity(string url, string gamertag)
        {
            _loadActivity = true;
            _textToDetect = gamertag;
            _bDefaultNavigate = false;

            //reload count
            int reloadCount = 0;

            //while the reload count does not exceed the max reload count
            while (reloadCount < _maxReload)
            {
                //request the page
                _srcReceived = false;
                webBrowser.Navigate(url);
                log("Not Received");
                //wait for an answer
                while (!_srcReceived)
                {
                    Thread.Sleep(100);
                    //log("Loop Received : "+_srcReceived.ToString());
                }
                log("Received");
                _bThreadStarted = false;
                //if error then reload
                if (_finalString == "ERROR")
                    ++reloadCount;
                else
                    return _finalString;
            }

            return _finalString;
        }

        public string navigate(string url)
        {
            //request the page
            _srcReceived = false;
            _bDefaultNavigate = true;
            webBrowser.Navigate(url);
            

            //wait for an answer
            while (!_srcReceived)
            {
                Thread.Sleep(100);
            }
            
            _bThreadStarted = false;
            
            return _finalString;
        }

        /// <summary>
        /// Event launched when the document is completed
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void webBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            //log("Document completed");
            //get the web browser
            WebBrowser b = (WebBrowser)sender;

            if (b.Url.ToString() == "about:blank")
            {
                _finalString = "about:blank";
                _srcReceived = true;
                return;
            }
            else if (_bDefaultNavigate)
            {
                _finalString = b.DocumentText;
                _srcReceived = true;
            }

            //refresh if error
            if (b.DocumentText.Contains("<!--Error Body-->"))
                b.Refresh();

            if (!_loadActivity)
            {
                _finalString = b.DocumentText;

                if (!_bThreadStarted)
                {
                    _bThreadStarted = true;
                    Thread newT = new Thread(new ThreadStart(checkAchievementsListLoaded));
                    newT.IsBackground = true;
                    newT.Start();          
                }
            }
            else
            {
                _doc = (mshtml.HTMLDocument)b.Document.DomDocument;

                if (!_bThreadStarted)
                {
                    log("Document completed : start thread");
                    _bThreadStarted = true;
                    Thread newT = new Thread(new ThreadStart(checkGamesListLoaded));
                    newT.IsBackground = true;
                    newT.Start();                    
                }
            }

            return;
        }
    }
}
